<?php
namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use think\controller;
use think\Db;

class Role extends UserAuth{
    public function index(){
        return $this->fetch('role');
    }
    /**
     * 角色列表
     * @param array $array 角色列表信息
     * @author 王柯 <25076778@qq.com>
     */
    public function role(){
        if(request()->isGet()){
            $keywords = trim(input('get.keywords'));
            $where = ['title'=> ['like', "%{$keywords}%"]];
            if(empty($keywords)){
                $roles = Db::name('auth_group')->select();
                $count = Db::name('auth_group')->count();
            }else{
                $roles = Db::name('auth_group') ->where($where)->select();
                $count = Db::name('auth_group')
                    ->where($where)
                    ->count();
            }
            $this->assign('count',$count);
            $this->assign('roles',$roles);
        }

        return $this->fetch('role');
    }
    /**
     * 角色详情显示
     * @param array $role 角色信息
     * @author 王柯 <25076778@qq.com>
     */
    public function role_show($id){
        $role = Db('auth_group')
            ->where('id='.$id)
            ->find();
        //dump($role);die;
        $this->assign('role',$role);
        return $this->fetch('role_show');
    }
    /**
     * 新增角色ajax
     * @param array $rules 所有角色
     * @param array $arr 权限id
     * @param string $str 拼接的权限
     * @param int $status0 新增角色失败状态
     * @param int $status1 新增角色成功状态
     * @author 王柯 <25076778@qq.com>
     * @return \think\response\Json
     */
    public function add_role(){
        $data = Db('auth_rule')
            ->where(['pid'=>0])
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['children'] = Db('auth_rule')
                ->where(['pid'=>$v['id']])
                ->select();
            foreach ($data[$k]['children'] as $k1 => $v1) {
                $data[$k]['children'][$k1]['children'] = Db('auth_rule')
                    ->where(['pid'=>$v1['id']])
                    ->select();
            }
        }
        if(request()->isAjax()){
            $data = $_GET;
            //验证
            $validate = validate('auth_group');
            if(!$validate->check($data)){
                return show(config('code.error'),$validate->getError());
            }
            if(!empty($data['rules'])){
                $data['rules'] = implode(',',$data['rules']);
            }else{
                $data['rules'] = '';
            }

            $role = new AuthGroup();
            $result = $role
                ->allowField(true)
                ->save($data);
            if($result){
                $uid = $role
                    ->getLastInsID();
                $auth_group_access = new AuthGroupAccess();
                $auth_group_access->data([
                    'uid' => $uid,
                    'group_id' => $uid
                ]);
                if($auth_group_access->save()){
                    return show(config('code.success'),'添加角色成功');
                }else{
                    return show(config('code.error'),'添加角色失败');
                }
            }
        }
        $rules = Db::table('book_auth_rule')
            ->select();
        $this->assign('data',$data);
        $this->assign('rules',$rules);
        return $this->fetch('add_role');
    }
    /**
     * 编辑角色ajax
     * @param array $arr 权限id
     * @param string $str 拼接的权限
     * @param int 0 编辑角色失败状态
     * @param int 1 编辑角色成功状态
     * @author 王柯 <25076778@qq.com>
     * @return \think\response\Json
     */
    public function edit_role($id){
        $data = Db('auth_rule')
            ->where(['pid'=>0])
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['children'] = Db('auth_rule')
                ->where(['pid'=>$v['id']])
                ->select();
            foreach ($data[$k]['children'] as $k1 => $v1) {
                $data[$k]['children'][$k1]['children'] = Db('auth_rule')
                    ->where(['pid'=>$v1['id']])
                    ->select();
            }
        }
        if(request()->isAjax()){
            $data = $_GET;
            //验证
            $validate = validate('auth_group');
            if(!$validate->check($data)){
                return json($validate->getError());
            }
            if(!empty($data['rules'])){
                $data['rules'] = implode(',',$data['rules']);
            }else{
                $data['rules'] = '';
            }
            $auth_group = new AuthGroup();
            $save = $auth_group
                ->where('id='.$data['id'])
                ->update($data);
            if($save){
                return show(config('code.success'),'编辑角色成功！');
            }else{
                return show(config('code.error'),'编辑角色失败');
            }
        }
        $rules = Db::table('book_auth_rule')
            ->select();
        $auths = Db::table('book_auth_group')
            ->where('id='.$id)
            ->find();
        $array = explode(',',$auths['rules']);
        $this->assign('data',$data);
        $this->assign('array',$array);
        $this->assign('rules',$rules);
        $this->assign('auths',$auths);
        return $this->fetch('edit_role');
    }

    /**
     * 删除角色ajax
     * @param array $user 会员信息
     * @param int 0 删除角色失败状态
     * @param int 1 删除角色成功状态
     * @author 王柯 <25076778@qq.com>
     * @return \think\response\Json
     */
    public function del_role(){
        if(request()->isAjax()){
            $user = Db::name('user')
                ->where('user_auth='.$_GET['id'])
                ->find();
            if(empty($user)){
                $role = new AuthGroup();
                $result = $role
                    ->where('id='.$_GET['id'])
                    ->delete();
                if($result){
                    return show(config('code.success'),'删除成功！');
                }else{
                    return show(config('code.error'),'删除失败！');
                }
            }else{
                return show(config('code.error'),'操作失败！');
            }
        }
    }

    /**
     * 批量删除
     * @author 巫玉梅 <1120504614@qq.com>
     * @return
     */
    public function batch_del_role(){
        if(request()->isAjax()){
            try{
                $data = $_POST;
                if(!empty($data['id'])){
                    $arr_id = $data['id'];
                    $str = implode(',',$arr_id);
                    $del = Db::name('auth_group')
                        ->where('id','in',$str)
                        ->delete();
                    if($del){
                        return show(config('code.success'),'批量删除成功！');
                    }else{
                        return show(config('code.error'),'批量删除失败！');
                    }
                }else{
                    return show(config('code.error'),'没有选中要删除的！');
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }
    //角色停用ajax
    public function stop_role_ajax(){
        if(request()->isAjax()){
            $id = $_POST['id'];
            $user = Db::name('auth_group')
                ->where('id='.$id)
                ->find();
            if($user['stop_status'] == 1){
                $_POST['stop_status'] = 0;
                $auth_group = new AuthGroup();
                $update = $auth_group
                    ->where('id='.$id)
                    ->update($_POST);
                if($update){
                    return show(config('code.success'),'操作成功！');
                }else{
                    return show(config('code.error'),'操作失败！');
                }
            }
        }
    }
    //角色启用ajax
    public function start_role_ajax(){
        $id = $_POST['id'];
        $role = Db::name('auth_group')
            ->where('id='.$id)
            ->find();
        if($role['stop_status'] == 0){
            $_POST['stop_status'] = 1;
            $auth_group = new AuthGroup();
            $update = $auth_group
                ->where('id='.$id)
                ->update($_POST);
            if($update){
                return show(config('code.success'),'操作成功！');
            }else{
                return show(config('code.error'),'操作失败！');
            }
        }
    }
}